﻿/***************************************************
 *
 *功能：获取企业微信信息，配置网页JS-SDK
 *
 * 状态：启用
 * 2018-06-23：添加公共方法TryGetWxCorpInfo
 **************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using com.nm.ApiServer;
using com.nm.db.Models.Terminal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin;
using Senparc.Weixin.Work;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.AdvancedAPIs.Chat;
using Senparc.Weixin.Work.AdvancedAPIs.LoginAuth;
using Senparc.Weixin.Work.AdvancedAPIs.Mass;
using Senparc.Weixin.Work.AdvancedAPIs.OAuth2;
using Senparc.Weixin.Work.Containers;
using Senparc.Weixin.Work.Entities;
using Senparc.Weixin.Work.Helpers;
using WeiXinAPI.Common;
using WeiXinAPI.model;

namespace WeiXinAPI
{
    public class WXBaseHandler:BaseHandler
    {
        public string BaseUrl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={WxWorkConfig.CorpId}&redirect_uri={0}&response_type=code&scope=SCOPE&agentid={WxWorkConfig.AgentId}&state=STATE#wechat_redirect";

        public ApiResult GetUser(string Code)
        {
            var accessToken = AccessTokenContainer.TryGetToken(WxWorkConfig.CorpId, WxWorkConfig.ContactsSecret);
            JsApiTicketContainer.Register(WxWorkConfig.CorpId, WxWorkConfig.ContactsSecret);
            
            var user= OAuth2Api.GetUserId(accessToken, Code);

            //TODO:获取报表用户权限GetConfig

            return Success(user);
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="wxConfig"></param>
        /// <returns></returns>
        public ApiResult GetDbUser(string Code, string wxConfig)
        {
            var isGuid = Guid.TryParse(wxConfig, out Guid newGuid);
            if (!isGuid) return Error("参数异常");
            GetUserInfoResult user = null;
            var dc = new TerminalEntities();
            var wxInfo = dc.CorpWX_Info.FirstOrDefault(t => t.CIdentification == newGuid && t.Enable);
            if (wxInfo !=null)
            {
                var accessToken = AccessTokenContainer.TryGetToken(wxInfo.CorpID, wxInfo.CorpSercet);
                JsApiTicketContainer.Register(wxInfo.CorpID, wxInfo.CorpSercet);
                user = OAuth2Api.GetUserId(accessToken, Code);
            }
            return Success(user);
        }

        /// <summary>
        /// 发送文本消息
        /// 注意：微信的文本消息支持的HTML只有a标签，不要用HTML来排版
        /// </summary>
        /// <returns></returns>
        public ApiResult SendMsg()
        {
            var accessToken = AccessTokenContainer.TryGetToken(WxWorkConfig.CorpId, WxWorkConfig.AppSecret);
            var result = MassApi.SendText(accessToken, WxWorkConfig.AgentId.ToString(), "测试消息", "CaiDongMing", null, null, 1);
            return Success(result.errcode == ReturnCode_Work.请求成功);
        }

        /// <summary>
        /// 发送文本卡片消息
        /// 注意：卡片消息支持使用br标签或者空格来进行换行处理，也支持使用div标签来使用不同的字体颜色，目前内置了3种文字颜色：灰色(gray)、高亮(highlight)、默认黑色(normal)，将其作为div标签的class属性即可
        /// </summary>
        /// <returns></returns>
        public ApiResult SendTextCardMsg()
        {
            var result = new MassResult();
            var textCard = new TextCardModel();
            var dc = new TerminalEntities();
            var accessToken = AccessTokenContainer.TryGetToken(WxWorkConfig.CorpId, WxWorkConfig.AppSecret);
            var sendSettings = dc.AutoSend_Setting.ToList();
           
            //每条记录
            foreach (var send in sendSettings)
            {
                var template = dc.AutoSend_MsgTemplate.FirstOrDefault(x => x.Id == send.TemplateId && x.Enable);
                if (template == null)
                {
                    return Error("找不到对应的模板");
                }

                var url = template.Url;
                if (send.ReportId != 0)
                {
                    url = url + "?reportid=" + send.ReportId; //跳报表参数
                    url = String.Format(BaseUrl, HttpUtility.UrlEncode(url));//为了拿code
                }

                textCard.AccessToken = accessToken;
                textCard.AgentId = WxWorkConfig.AgentId.ToString();
                textCard.Title = template.Title;
                textCard.Description = template.Description;
                textCard.Url = url;
                textCard.Btntxt = template.Btntxt;
                textCard.ToUser = send.UserIds;

                result = MassApi.SendTextCard(textCard.AccessToken, textCard.AgentId, textCard.Title, textCard.Description, textCard.Url, textCard.Btntxt, textCard.ToUser);


            }

            return Success(result.errcode == ReturnCode_Work.请求成功);
        }

        /// <summary>
        /// 发送图文消息
        /// 注意：微信的文本消息支持的HTML只有a标签，不要用HTML来排版
        /// </summary>
        /// <returns></returns>
        public ApiResult SendNewsMsg()
        {
            var result = new MassResult();
            var news = new NewsModel();
            var dc = new TerminalEntities();

            var accessToken = AccessTokenContainer.TryGetToken(WxWorkConfig.CorpId, WxWorkConfig.AppSecret);
            var sendSettings = dc.AutoSend_Setting.ToList();

            //每条记录
            foreach (var send in sendSettings)
            {
                var template = dc.AutoSend_MsgTemplate.FirstOrDefault(x => x.Id == send.TemplateId && x.Enable);
                if (template == null)
                {
                    return Error("找不到对应的模板");
                }

                news.AccessToken = accessToken;
                news.AgentId = WxWorkConfig.AgentId.ToString();
                news.Articles = new List<Article>()
                {
                    new Article()
                    {
                        Description = template.Description,
                        Title = template.Title,
                        Url = template.Url,
                        PicUrl = template.PicUrl
                    }
                };
                news.ToUser = send.UserIds;

                result = MassApi.SendNews(news.AccessToken, news.AgentId, news.Articles,  news.ToUser);
            }

            return Success(result.errcode == ReturnCode_Work.请求成功);
        }

        #region 验证并尝试获取企业微信配置信息 TryGetWxCorpInfo

        /// <summary>
        /// 验证并尝试获取企业微信配置信息
        /// </summary>
        /// <param name="wxConfig"></param>
        /// <returns></returns>
        public static WxCorpInfoResult TryGetWxCorpInfo(string wxConfig)
        {
            var isGuid = Guid.TryParse(wxConfig, out Guid newGuid);
            if (!isGuid)
            {
                return new WxCorpInfoResult()
                {
                    Message = "wxConfig参数异常"
                };
            }

            var dc = new TerminalEntities();
            var wxInfo = dc.CorpWX_Info.FirstOrDefault(t => t.CIdentification == newGuid && t.Enable);
            if (wxInfo == null)
            {
                return new WxCorpInfoResult()
                {
                    Message = "获取数据列表失败"
                };
            }

            return new WxCorpInfoResult()
            {
                CorpInfo = wxInfo
            };
        }

        #endregion

        #region 使用JS-SDK的页面所需的注入配置信息 GetConfig

        /// <summary>
        /// 使用JS-SDK的页面所需的注入配置信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetConfig(string url, string wxConfig)
        {
            var isGuid = Guid.TryParse(wxConfig, out Guid newGuid);
            if (!isGuid) return Error("参数异常");
            var dc = new TerminalEntities();
            var wxInfo = dc.CorpWX_Info.FirstOrDefault(t => t.CIdentification == newGuid && t.Enable);
            if (wxInfo != null)
            {
                var timeStamp = JSSDKHelper.GetTimestamp();
                var nonceStr = JSSDKHelper.GetNoncestr();
                var ticket = JsApiTicketContainer.TryGetTicket(wxInfo.CorpID, wxInfo.CorpSercet);
                var signature = JSSDKHelper.GetSignature(ticket, nonceStr, timeStamp, url);

                var result = new jssdkConfig
                {
                    timeStamp = timeStamp,
                    nonceStr = nonceStr,
                    signature = signature,
                    ticket = ticket,
                    corpId = wxInfo.CorpID
                };
                return Success(result);
            }
            return Error("配置JS-SDK失败");
        }

        #endregion
    }



    public class TextCardModel
    {
        public string AccessToken { get; set; }
        public string AgentId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Url { get; set; }
        public string Btntxt { get; set; }
        public string ToUser { get; set; }
        public string ToParty { get; set; }
        public string ToTag { get; set; }
        public int TimeOut { get; set; }
    }


    public class NewsModel
    {
        public string AccessToken { get; set; }
        public string AgentId { get; set; }

        //=========================================public string PicUrl { get; set; }

        public List<Article> Articles { get; set; }

        public string ToUser { get; set; }

        public string ToParty { get; set; }
        public string ToTag { get; set; }

        public int Safe { get; set; }

        public int TimeOut { get; set; }
    }


    public class MpNewsModel
    {
        public string AccessToken { get; set; }
        public string AgentId { get; set; }

        //=========================================public string PicUrl { get; set; }

        public List<MpNewsArticle> Articles { get; set; }

        public string ToUser { get; set; }

        public string ToParty { get; set; }
        public string ToTag { get; set; }

        public int Safe { get; set; }

        public int TimeOut { get; set; }
    }
}
